﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace MSATracert
{
#pragma warning disable CS1591
    public class LinkTracertHttpHandler : DelegatingHandler
    {
        private readonly bool tokenRelay;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="tokenRelay">是否继续传递token</param>
        public LinkTracertHttpHandler(bool tokenRelay) : base(new HttpClientHandler())
        {
            this.tokenRelay = tokenRelay;
        }
        public LinkTracertHttpHandler() : this(false)
        {

        }
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var principal = Thread.CurrentPrincipal as LinkTracertPricipal;
            string traceId = principal?.RequestId ?? Guid.NewGuid().ToString("N").ToLower();
            if (!string.IsNullOrEmpty(principal?.IPAddress))
            {
                request.Headers.TryAddWithoutValidation("X-Forwarded-For", principal.IPAddress);
            }

            //忽略脱敏
            request.Headers.TryAddWithoutValidation("X-Sensitive", "3aed2fe84efb0f3b3106db8697060e93");
            request.Headers.UserAgent.Clear();
            request.Headers.UserAgent.Add(new System.Net.Http.Headers.ProductInfoHeaderValue("APIContract", "v1.0.0"));

            if (this.tokenRelay && principal != null && principal.Tokens.Count > 0)
            {
                foreach (var token in principal.Tokens)
                {
                    if (!string.IsNullOrEmpty(token.Name) && !string.IsNullOrEmpty(token.Value))
                    {
                        request.Headers.TryAddWithoutValidation(token.Name, token.Value);
                    }
                }
            }
            if (!request.Headers.TryAddWithoutValidation(LinkTracertPricipal.HEADER_NAME, traceId))
            {
                Debug.WriteLine("LinkTracertHttpHandler Fail to add header X-Connection-Id:" + traceId);
            }
            return base.SendAsync(request, cancellationToken);
        }
    }
#pragma warning restore CS1591
}
